package net.ck.hzq;

import android.Manifest;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.content.ContextCompat;
import android.support.v4.util.ArrayMap;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.FrameLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.jakewharton.rxbinding.widget.RxRadioGroup;
import com.kf5.sdk.system.entity.Field;
import com.kf5.sdk.system.entity.ParamsKey;
import com.kf5.sdk.system.init.UserInfoAPI;
import com.kf5.sdk.system.internet.HttpRequestCallBack;
import com.kf5.sdk.system.utils.SPUtils;
import com.kf5.sdk.system.utils.SafeJson;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.ref.SoftReference;
import java.util.Map;

import Bean.UpdateBean;
import Utils.ApkversioncodeUtils;
import base.BaseAct;
import base.BaseBiz;
import butterknife.BindView;
import coom.Constants;
import coom.MyType;
import coom.RetrofitHelp;
import event.CloseActEvent;
import event.MessageEvent;
import event.NetErrorEvent;
import home.NewHomeFragment;
import rx.functions.Action1;
import ui.activity.partner.PartnerFra;
import ui.activity.profit.biz.ProfitBiz;
import ui.fragment.AchievementFra;
import ui.fragment.MyFragment;
import util.Kf5BaseUtils;
import util.LogUtils;

public class MainActivity extends BaseAct {


    @BindView(R.id.main_framelayout)
    FrameLayout content;
    @BindView(R.id.homepage)
    RadioButton homepage;
    @BindView(R.id.profit)
    RadioButton profit;
    @BindView(R.id.partner)
    RadioButton partner;
    @BindView(R.id.mine)
    RadioButton mine;
    @BindView(R.id.navi)
    RadioGroup navi;

    @BindView(R.id.message_number)
    TextView number;


    long time = 0;

    FragmentManager fm;
    Fragment cf;//记录当前fragment
    String ct;//当前tag

    private Fragment homeFra;
    private Fragment profitFra;
    private Fragment partnerFra;
    private Fragment mineFra;

    public final static String HOME = "首页";
    public final static String PROFIT = "业绩";
    public final static String PARTNER = "合伙人";
    public final static String MINE = "我的";
    private final static String TAG = "current_fragment";


    private SharedPreferences sp;

//    @Override
//    protected void setTitleBar(String color) {
//        super.setTitleBar("#7114F8");
//    }

    @Override
    protected void setRoot() {
        requestWindowFeature(Window.FEATURE_NO_TITLE); // 隐藏标题栏
        setContentView(R.layout.activity_main);
        TobuyApplication.getmInstance().onActivityCreate(this);
    }

    @Override
    protected void init(@Nullable Bundle savedInstanceState) {
        sp = getSharedPreferences("ToBuy", Context.MODE_PRIVATE);
        String phoneNumber = sp.getString("phonenumber", "");
        String userId = sp.getString("id", "0");
        String realName = sp.getString("realname", "");
        upDataUI(userId, realName, phoneNumber);
//        HelloWordModel.getInstance(MainActivity.this).
//        updateapp(MainActivity.this, sp);
        int permission = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (permission != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new
                    String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
        }
        fm = getSupportFragmentManager();
        if (savedInstanceState != null) {
            try {
                homeFra = fm.findFragmentByTag(HOME);
                profitFra = fm.findFragmentByTag(PROFIT);
                partnerFra = fm.findFragmentByTag(PARTNER);
                mineFra = fm.findFragmentByTag(MINE);

                for (Fragment fra : fm.getFragments()) {
                    if (!fra.isHidden()) {
                        fm.beginTransaction().hide(fra).commit();
                    }
                    switch ((int) savedInstanceState.getSerializable(TAG)) {
                        case R.id.homepage:
                            homepage.setChecked(true);
                            break;
                        case R.id.profit:
                            profit.setChecked(true);
                            break;
                        case R.id.partner:
                            partner.setChecked(true);
                            break;
                        case R.id.mine:
                            mine.setChecked(true);
                            break;
                    }
                }
            } catch (Exception e) {
            }
        }
        RxRadioGroup.checkedChanges(navi)
                .compose(this.<Integer>bindToLifecycle())
//                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(new Action1<Integer>() {
                    @Override
                    public void call(Integer integer) {
                        switch (integer) {
                            case R.id.homepage:
                                if (homeFra == null) {
                                    homeFra = new NewHomeFragment();
                                }
                                changFra(homeFra, HOME);
                                break;
                            case R.id.profit:
                                if (profitFra == null) {
                                    profitFra = new AchievementFra();
                                }
                                changFra(profitFra, PROFIT);
                                break;
                            case R.id.partner:
                                if (partnerFra == null) {
                                    partnerFra = new PartnerFra();
                                }
                                changFra(partnerFra, PARTNER);
                                break;
                            case R.id.mine:
                                if (mineFra == null) {
                                    mineFra = new MyFragment();
                                }
                                changFra(mineFra, MINE);
                                break;
                        }
                    }
                });
        homepage.setChecked(true);
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onCloseActEvent(CloseActEvent event) {
        if (event.getType() == MyType.Logout) {
            finishAct();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 1 && grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

        }
    }

    private void changFra(Fragment fra, String tag) {
        ct = tag;
        if (fm.findFragmentByTag(tag) == null) {
            if (cf != null) {
                fm.beginTransaction().hide(cf).add(R.id.main_framelayout, fra, tag).commit();
            } else {
                fm.beginTransaction().add(R.id.main_framelayout, fra, tag).commit();
            }
            cf = fra;
            return;
        }
        if (fra.isHidden()) {
            if (cf != null) {
                fm.beginTransaction().hide(cf).show(fra).commit();
            } else {
                fm.beginTransaction().show(fra).commit();
            }
            cf = fra;
        }
    }


    @Override
    public void onBackPressed() {
//        super.onBackPressed();
        moveTaskToBack(false);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    protected void onNetError(NetErrorEvent event) {

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEvent event) {
        if (event.getNumber() == 0) {
            number.setVisibility(View.INVISIBLE);
        } else {
            number.setText(event.getNumber() + "");
            number.setVisibility(View.VISIBLE);
        }
    }
    //    @Override
//    public boolean onKeyDown(int keyCode, KeyEvent event) {
//        if (keyCode == KeyEvent.KEYCODE_BACK) {
//            if (System.currentTimeMillis() - time > 2000) {
//                Toast.makeText(getApplicationContext(), "再按一次退出应用?", Toast.LENGTH_SHORT).show();
//                time = System.currentTimeMillis();
//            } else {
////                TobuyApplication.getmInstance().finishAllActivity();
//                finish();
//            }
//            return false;
//        } else
//            return false;
//    }


    /**
     * 登录客服系统
     */

    Map<String, String> map = new ArrayMap<>();

    private void loginUser(final Map<String, String> map) {
        UserInfoAPI.getInstance().loginUser(map, new HttpRequestCallBack() {
            @Override
            public void onSuccess(final String result) {
                LogUtils.d("kf5测试", "登录成功" + result);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            final JSONObject jsonObject = SafeJson.parseObj(result);
                            int resultCode = SafeJson.safeInt(jsonObject, "error");
                            if (resultCode == 0) {
                                final JSONObject dataObj = SafeJson.safeObject(jsonObject, Field.DATA);
                                JSONObject userObj = SafeJson.safeObject(dataObj, Field.USER);
                                if (userObj != null) {
                                    String userToken = userObj.getString(Field.USERTOKEN);
                                    int id = userObj.getInt(Field.ID);
                                    SPUtils.saveUserToken(userToken);
                                    SPUtils.saveUserId(id);
                                    saveToken(map, userToken);
                                }
                            } else {
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        try {
                                            String message = jsonObject.getString("message");
                                            Toast.makeText(MainActivity.this, message, Toast.LENGTH_SHORT).show();
                                        } catch (JSONException e) {
                                            e.printStackTrace();
                                        }
                                    }
                                });
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });

            }

            @Override
            public void onFailure(String result) {
                LogUtils.d("kf5测试", "登录失败" + result);
                Constants.CustomerOline = false;
            }
        });
    }


    private void saveToken(Map<String, String> map, String token) {
        map.put(ParamsKey.DEVICE_TOKEN, token);
        UserInfoAPI.getInstance().saveDeviceToken(map, new HttpRequestCallBack() {
            @Override
            public void onSuccess(String result) {
                LogUtils.d("kf5测试", "保存设备Token成功" + result);
            }

            @Override
            public void onFailure(String result) {
                LogUtils.d("kf5测试", "保存设备Token失败" + result);
                Constants.CustomerOline = false;
            }
        });

        UserInfoAPI.getInstance().getUserInfo(map, new HttpRequestCallBack() {
            @Override
            public void onSuccess(String result) {

            }

            @Override
            public void onFailure(String result) {

                Constants.CustomerOline = false;
            }
        });
    }

    private void createUser() {
        LogUtils.d(map.toString());
        SPUtils.saveUserAgent(Kf5BaseUtils.getAgent(new SoftReference<Context>(MainActivity.this)));
        UserInfoAPI.getInstance().createUser(map
                , new HttpRequestCallBack() {
                    @Override
                    public void onSuccess(final String result) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    final JSONObject jsonObject = SafeJson.parseObj(result);
                                    int resultCode = SafeJson.safeInt(jsonObject, "error");
                                    if (resultCode == 0) {
                                        final JSONObject dataObj = SafeJson.safeObject(jsonObject, Field.DATA);
                                        JSONObject userObj = SafeJson.safeObject(dataObj, Field.USER);
                                        if (userObj != null) {
                                            String userToken = userObj.getString(Field.USERTOKEN);
                                            int id = userObj.getInt(Field.ID);
                                            SPUtils.saveUserToken(userToken);
                                            SPUtils.saveUserId(id);
                                            saveToken(map, userToken);
                                        }
                                        LogUtils.d("kf5测试", "登录成功" + result);
                                    } else {
                                        runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                loginUser(map);
                                                LogUtils.d("kf5测试开始登录");
                                            }
                                        });
                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                        });
                    }

                    @Override
                    public void onFailure(String result) {
                        LogUtils.d("kf5测试", "登录失败" + result);
                        Constants.CustomerOline = false;
                    }
                });

    }


    public void upDataUI(String id, String name, String phone) {
        try {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put(ParamsKey.PHONE, phone);
            jsonObject.put(ParamsKey.VALUE, id);
            jsonObject.put(ParamsKey.NAME, name);
            map.put(ParamsKey.USER_FIELDS, jsonObject.toString());
            map.put(ParamsKey.NAME, name);
            map.put(ParamsKey.PHONE, phone);
            map.put(ParamsKey.EMAIL, id + "@forcard.com");
            createUser();
        } catch (Exception e) {

        }

    }
    public void updateapp(final Context context, SharedPreferences sp) {

        ProfitBiz biz = new ProfitBiz();

        biz.updateversion(RetrofitHelp.BASE_URL + "api/version?terminal=1", new BaseBiz.Callback<UpdateBean>() {
            @Override
            public void onSuccess(UpdateBean updateBean) {
                Log.e("fjs", ApkversioncodeUtils.getVersionCode(context) + "");

                try {
                int onlineVersion = Integer.parseInt(updateBean.getVersion());
                if (ApkversioncodeUtils.getVersionCode(context)<onlineVersion) {
                    showNoticeDialog(context, updateBean.getUrl(), updateBean.getLevel(), updateBean.getTip() + "");
                }

                }catch (Exception e){

                }
            }

            @Override
            public void onFailure(UpdateBean updateBean) {

            }
        });
    }
    private void showNoticeDialog(final Context context, final String downUrl,int level,String content) {
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setTitle(R.string.soft_update_title);
        builder.setMessage(content);
        if(level == 1){
            builder.setPositiveButton(R.string.soft_update_updatebtn,
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            showDownloadDialog(context, downUrl);
                            finishAct();
                        }
                    });
        }else {
            builder.setPositiveButton(R.string.soft_update_updatebtn,
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            showDownloadDialog(context, downUrl);
                            finishAct();
                        }
                    });
            builder.setNegativeButton(R.string.soft_update_later,
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });
        }
        builder.setCancelable(false);
        Dialog noticeDialog = builder.create();
        noticeDialog.show();
    }

    private void showDownloadDialog(Context context, String downUrl) {
//        ToastUtils.shortToast("开始下载...");
//        Intent intent = new Intent(context, DownloadService.class);
//        intent.putExtra("url", downUrl);

        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(downUrl));
        context.startActivity(intent);

//        context.startService(intent);
    }
}
